<template>
  <view class="wrap">
    <u-toast ref="uToast"></u-toast>
    <uni-card>
      <u-form class="form" :model="feedback" :rules="rules" ref="uForm" label-position="top" :labelWidth="300">
        <u-form-item label="问题和意见" prop="content">
          <u-textarea v-model="feedback.content" placeholder="请填写10个字以上的问题描述以便我们提供更好的帮助"></u-textarea>
        </u-form-item>
        <u-form-item label="联系方式（手机、邮箱、QQ号码）" prop="phone">
          <u-input class="input-left-form" placeholder="选填，便于我们与你联系，进一步沟通" v-model="feedback.phone" type="text" maxlength="11"></u-input>
        </u-form-item>
        <u-form-item label="图片">
          <u-upload :previewFullImage="true" :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="5" multiple :maxCount="1"></u-upload>
        </u-form-item>
      </u-form>
      <view class="form-footer">
        <u-button class="btn" type="primary" @click="submit">提交</u-button>
        <u-button class="btn" type="default" @click="cancel">取消</u-button>
      </view>
    </uni-card>

  </view>
</template>

<script>
export default {
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules)
  },
  data() {
    return {
      feedback: {
        content: '',
        phone: ''
      },
      rules: {
        content: {
          type: 'string',
          required: true,
          message: '请填内容',
          trigger: ['blur', 'change']
        },
        phone: {
          type: 'string',
          pattern: /1\d{10}/,
          required: true,
          message: '请输入正确机号',
          trigger: ['blur', 'change']
        }
      },
      fileList: []
    }
  },
  methods: {
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1)
    },
    // 新增图片
    afterRead(event) {
      console.log(event)
      let fileList = event.file
      uni.uploadFile({
        url: 'http://127.0.0.1:80/upload', // 仅为示例，非真实的接口地址
        filePath: fileList[0].url,
        name: 'file',
        formData: {
          folderName: 'test'
        },
        success: ({ data }) => {
          let back = JSON.parse(data)
          this.fileList.push('http://127.0.0.1:80' + back.data.filePath)
        }
      })
    },
    async submit() {
      // console.log(this.model)
      try {
        let back = await this.$refs.uForm.validate()
        uni.$u.toast('保存成功')
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/center/center'
          })
        }, 2000)
      } catch (error) {
        uni.$u.toast('请检查数据')
      }
    },
    cancel() {
      uni.switchTab({
        url: '/pages/center/center'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.input-placeholder {
  text-align: right;
}
</style>
